import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_oldman_health/api/constant.dart';
import 'package:flutter_oldman_health/api/health_data_service.dart';
import 'package:flutter_oldman_health/models/health_data_model.dart';
import 'package:flutter_oldman_health/models/relation_model.dart';
import 'package:flutter_oldman_health/utils/time_machine_util.dart';

import 'health_record_charts_page.dart';

class HealthRecordPage extends StatefulWidget {
  FamilyRelationItem item;

  HealthRecordPage(FamilyRelationItem relationItem) {
    this.item = relationItem;
  }

  @override
  HealthRecordPageState createState() {
    return HealthRecordPageState(item);
  }
}

class HealthRecordPageState extends State<HealthRecordPage> {
  List listData = ["血氧", "心率", "体温", "计步"];
  List listImageData = [
    "images/ic_blood oxygen.png",
    "images/ic_heart_rate.png",
    "images/ic_temperature.png",
    "images/ic_step_counting.png"
  ];
  List measuredLastValue = ["暂无数据", "暂无数据", "暂无数据", "暂无数据"];
  HealthData _healthData;
  FamilyRelationItem _item;
  Size screenSize;

  HealthRecordPageState(FamilyRelationItem item) {
    _item = item;
  }

  void queryHealthData() async {
    super.initState();
    //var response = await
    HealthDataService.queryHealthData(_item.memberId).then((response) {
      if (null != response && response.statusCode == 200) {
        HealthDataModel healthDataModel =
            HealthDataModel.fromJson(response.data);
        if (healthDataModel.success()) {
          setState(() {
            _healthData = healthDataModel.data;
            measuredLastValue = [
              (null != _healthData.bloodOxygen)
                  ? "${_healthData.bloodOxygen?.value?.toInt()}%"
                  : "暂无数据",
              (null != _healthData.heartRate)
                  ? "${_healthData.heartRate?.value?.toInt()} 次/分"
                  : "暂无数据",
              (null != _healthData.temperature)
                  ? _healthData.temperature?.value.toString() + " °C"
                  : "暂无数据",
              "暂无数据"
            ];
          });
        }
      }
    });
  }

  @override
  void initState() {
    super.initState();
    refresh();
  }

  void refresh() {
    queryHealthData();
    queryStepNumber();
  }

  @override
  Widget build(BuildContext context) {
    screenSize = MediaQuery.of(context).size;
    return Container(
        color: Constant.backgroundColor,
        child: Column(children: [
          _getTitle("健康记录"),
          Stack(children: [
            Image.asset("images/bg_home.png",
                alignment: AlignmentDirectional.center, fit: BoxFit.fill),

            Column(children: [
              Row(mainAxisAlignment: MainAxisAlignment.center, children: [
                _getHealthItem(0, EdgeInsets.fromLTRB(10, 10, 8, 0),
                    Color(0xffFF7B1A), Color(0xffFFAE40)),
                _getHealthItem(1, EdgeInsets.fromLTRB(8, 10, 10, 0),
                    Color(0xff4166FF), Color(0xff417BFF))
              ]),
              Row(mainAxisAlignment: MainAxisAlignment.center, children: [
                _getHealthItem(2, EdgeInsets.fromLTRB(10, 10, 8, 0),
                    Color(0xFFff4467), Color(0xffFF6767)),
                _getHealthItem(3, EdgeInsets.fromLTRB(8, 10, 10, 0),
                    Color(0xff23b9a1), Color(0xff3FB9AF))
              ])
            ])
            // GridView.count(
            //   // crossAxisSpacing: 10.0,
            //   // mainAxisSpacing: 10.0,
            //   // padding: EdgeInsets.all(10.0),
            //   crossAxisCount: 2,
            //   // childAspectRatio:0.7,  //宽度和高度的比例
            //   children: this._getListData3(),
            // )
          ])
        ]));
  }

  Widget _getHealthItem(
      int index, EdgeInsets margin, Color colorBegin, Color colorEnd) {
    return GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          Navigator.of(context)
              .push(MaterialPageRoute(builder: (BuildContext c) {
            return HealthRecordChartsPage(
                familyRelationItem: _item, healthRecordType: index);
            // serialData: index == 3 ? serialData : serial1data);
          })).then((value) {
            if (value) refresh();
          });
        },
        child: Container(
          margin: margin,
          width: screenSize.width / 2 - 28,
          height: screenSize.height / 2 - 75,
          padding: EdgeInsets.all(12),
          child: Column(children: <Widget>[
            Image.asset(listImageData[index]),
            Text(
              listData[index],
              textAlign: TextAlign.center,
              style: TextStyle(
                  fontSize: 19.0,
                  color: Colors.white,
                  decoration: TextDecoration.none),
            ),
            FractionallySizedBox(
              widthFactor: 1,
              child: Text(index == 3 ? "昨天步数" : "上次测量值:",
                  textAlign: TextAlign.left,
                  style: TextStyle(
                      fontSize: 17.0,
                      color: Colors.white,
                      decoration: TextDecoration.none)),
            ),
            Padding(padding: EdgeInsets.only(top: 10)),
            Text(measuredLastValue[index],
                textAlign: TextAlign.center,
                style: TextStyle(
                    fontSize: 22.0,
                    color: Colors.white,
                    decoration: TextDecoration.none)),
          ]),
          decoration: BoxDecoration(
              gradient: LinearGradient(
                  begin: AlignmentDirectional.topCenter,
                  end: AlignmentDirectional.bottomCenter,
                  colors: [colorBegin, colorEnd]),
              borderRadius: BorderRadius.circular(28)),
        ));
  }

  Widget _getTitle([String title = "成员姓名"]) {
    return Container(
        color: Constant.appbarColor,
        padding: EdgeInsets.fromLTRB(16, 46, 16, 16),
        child: FractionallySizedBox(
          widthFactor: 1,
          child: Stack(
            alignment: Alignment.center,
            children: [
              Positioned(
                left: 2,
                top: 5,
                child: GestureDetector(
                    behavior: HitTestBehavior.translucent,
                    onTap: () {
                      Navigator.pop(context);
                    },
                    child: Container(
                        child: Icon(Icons.arrow_back_ios),
                        padding: EdgeInsets.fromLTRB(15, 0, 20, 10))),
              ),
              Text(title,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      fontSize: 22,
                      color: Colors.black87,
                      fontWeight: FontWeight.normal))
            ],
          ),
        ));
  }

  void queryStepNumber() async {
    Map<String, String> timeMap = TimeMachineUtil.getWeeksDate(0);
    int startTime = int.parse(timeMap['monDayStamp']);
    int endTime = int.parse(timeMap['sunDayStamp']);

    var response = await HealthDataService.queryStepNumber(
        type: 1,
        memberId: widget.item.memberId,
        startTime: startTime,
        endTime: endTime);
    if (null != response && response.statusCode == 200) {
      setState(() {
        List<HealthAverageData> averageData =
            HealthAverageListModel.fromJson(response.data).data;
        if (averageData.isNotEmpty) {
          int index = 0;
          for (int i = 0; i < averageData.length; i++) {
            if (averageData[i].inDate > startTime &&
                (averageData[i].inDate > averageData[index].inDate)) {
              index = i;
            }
            if (i == averageData.length - 1 &&
                averageData[index].average != 0) {
              String average = averageData[index].average.toString();
              setState(() {
                measuredLastValue[3] =
                    average.substring(0, average.toString().indexOf(".")) + "步";
              });
            }
          }
        }
      });
    }
  }
}
